package main

import (
	"strconv"

	"github.com/astaxie/beego/orm"
)

// 链接数据库
func linkData(data map[string]interface{}) (map[string]interface{}, orm.Ormer) {
	data = dataUrl(data)
	dataType := data["dataType"].(string)
	dataUrl := data["dataUrl"].(string)
	var dataMap = make(map[string]interface{})
	var err error
	default_s := "default"
	if default_i > 0 {
		default_s = default_s + strconv.FormatInt(int64(default_i), 10)
	}
	default_i++
	orm.GetDB(default_s)
	if dataType == "mysql" {
		orm.RegisterDriver("mysql", orm.DRMySQL)
		err = orm.RegisterDataBase(default_s, "mysql", dataUrl)
	} else if dataType == "postgres" {
		orm.RegisterDriver("postgres", orm.DRPostgres)
		err = orm.RegisterDataBase(default_s, "postgres", dataUrl)
	} else if dataType == "oracle" {
		orm.RegisterDriver("oracle", orm.DROracle)
		err = orm.RegisterDataBase(default_s, "oracle", dataUrl)
	} else {
		dataMap["code"] = 300
		dataMap["msg"] = "数据库类型不匹配"
		return dataMap, nil
	}
	if err != nil {
		dataMap["code"] = 500
		dataMap["msg"] = err.Error()
		return dataMap, nil
	}
	dataMap["code"] = 200
	dataMap["msg"] = "连接成功"
	return dataMap, orm.NewOrm()
}
